package com.endava.action;


import com.endava.dao.BookDAO;
import com.endava.dao.impl.BookDAOImpl;
import com.endava.model.Book;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;

public class RegisterBookAction extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) {
        String bookName = req.getParameter("name");
        String author = req.getParameter("author");
        String releaseDate = req.getParameter("releaseDate");

        if (bookName == null || bookName.isEmpty() || author == null || author.isEmpty()) {
            Writer writer = null;
            try {
                writer = res.getWriter();
                writer.write("Please provide us the bookName and the author");
            } catch (IOException e) {
                System.out.println("Exception: " + e.getMessage());
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException e) {
                    System.out.println("Error on closing the writer");
                }
            }
        } else {
            BookDAO bookDAO = new BookDAOImpl();
            ((BookDAOImpl) bookDAO).setConnection((Connection) getServletContext().getAttribute("connection"));
            bookDAO.create(new Book(bookName, author, releaseDate));
        }
    }
}
